package org.example.config;

import org.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行登录接口和静态资源
        String uri = request.getRequestURI();
        if (uri.startsWith("/login") || uri.startsWith("/") || uri.startsWith("/css") || uri.startsWith("/js") || uri.startsWith("/img")) {
            return true;
        }

        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            response.getWriter().write("未登录或登录已失效");
            return false;
        }

        String userJson = redisUtil.get(token);
        if (userJson == null) {
            response.setStatus(401);
            response.getWriter().write("登录已失效，请重新登录");
            return false;
        }

        // 可在此设置用户信息到请求属性中，供后续使用
        request.setAttribute("userInfo", userJson);

        return true;
    }
}